package app

import (
	"fmt"
	"net/http"
	"sync/atomic"
	"time"
)

func init() {
	max = 10
	Gateway.PathMapping = append(Gateway.PathMapping, mapping{path: "/list", concurrent: 10, outTime: 10})

}

var max int32
var total int32
var num int32

type mapping struct {
	path       string
	concurrent int32
	outTime    int16
}
type gateway struct {
	PathMapping []mapping
}

var Gateway gateway

func init() {
	//context.WithDeadline(context.Background(), time.Now().Add(time.Second*10))
}
func (this *gateway) Action(r *http.Request, path string) {
	Gateway.LimitRequest().Add()
}

func (this *gateway) Add() {
	//fmt.Println("增加请求",total)
	atomic.AddInt32(&total, 1)
	fmt.Println("进程池中数量：", atomic.LoadInt32(&total))
	atomic.AddInt32(&num, 1)
}

func (this *gateway) Reduce(r *http.Request, path string) {
	//用apache的ab工具测试下效果 ab -n 200（请求次数） -c 11（并发数）127.0.0.1:8000/api
	time.Sleep(1 * time.Second)
	atomic.AddInt32(&total, -1)
	fmt.Println("减少1请求 总数:", atomic.LoadInt32(&total))
}

func (this *gateway) LimitRequest() *gateway {
	fmt.Println("请求次数", atomic.LoadInt32(&num))
	//超出并发数
	if atomic.LoadInt32(&total) >= max {
		//fmt.Println("达到请求上限，退出线程！",total)
		panic("达到请求上限，退出线程！")
	}
	return this
}
